

#include <multimedia/FormatoBMP.h>



MatrizRGBA* FormatoBMP::Decodificar(FluxoDeBytes* fluxo)
{
    BFH bfh;

    bfh.bfType      = fluxo->PegarBytes(2);
    bfh.bfSize      = fluxo->PegarBytes(4);
    bfh.bfReserved1 = fluxo->PegarBytes(2);
    bfh.bfReserved2 = fluxo->PegarBytes(2);
    bfh.bfOffBits   = fluxo->PegarBytes(4);
    
//    printf("bfType...........: %d\n", bfh.bfType);
//    printf("bfSize...........: %d\n", bfh.bfSize);
//    printf("bfReserved1......: %d\n", bfh.bfReserved1);
//    printf("bfReserved2......: %d\n", bfh.bfReserved2);
//    printf("bfOffBits........: %d\n", bfh.bfOffBits);

    BIH bih;
    
    bih.biSize          = fluxo->PegarBytes(4);
    bih.biWidth         = fluxo->PegarBytes(4);
    bih.biHeight        = fluxo->PegarBytes(4);
    bih.biPlanes        = fluxo->PegarBytes(2);
    bih.biBitCount      = fluxo->PegarBytes(2);
    bih.biCompression   = fluxo->PegarBytes(4);
    bih.biSizeImage     = fluxo->PegarBytes(4);
    bih.biXPelsPerMeter = fluxo->PegarBytes(4);
    bih.biYPelsPerMeter = fluxo->PegarBytes(4);
    bih.biClrUsed       = fluxo->PegarBytes(4);
    bih.biClrImportant  = fluxo->PegarBytes(4);

//    printf("biSize...........: %d\n", bih.biSize);
//    printf("biWidth..........: %d\n", bih.biWidth);
//    printf("biHeight.........: %d\n", bih.biHeight);
//    printf("biPlanes.........: %d\n", bih.biPlanes);
//    printf("biBitCount.......: %d\n", bih.biBitCount);
//    printf("biCompression....: %d\n", bih.biCompression);
//    printf("biSizeImage......: %d\n", bih.biSizeImage);
//    printf("biXPelsPerMeter..: %d\n", bih.biXPelsPerMeter);
//    printf("biYPelsPerMeter..: %d\n", bih.biYPelsPerMeter);
//    printf("biClrUsed........: %d\n", bih.biClrUsed);
//    printf("biClrImportant...: %d\n", bih.biClrImportant);


    MatrizRGBA* matriz = new MatrizRGBA(bih.biWidth, bih.biHeight);
    
    switch(bih.biBitCount)
    {
        case 24:
        {
            int largura = bih.biWidth  * 3;
            int altura  = bih.biHeight * 3;
            int larguraOcupada = (largura%4)? ((largura/4)+1)*4 : largura;
            int alturaOcupada  = altura;
            
            for(int j=matriz->Altura()-1; j>=0; j--)
            {
                for(int i=0; i<matriz->Largura(); i++)
                {
                    register unsigned char bandaB = fluxo->PegarBytes(1);
                    register unsigned char bandaG = fluxo->PegarBytes(1);
                    register unsigned char bandaR = fluxo->PegarBytes(1);

                    (*matriz)[i][j] = RGBA(bandaR,bandaG,bandaB,255);
                    
                }

                fluxo->PegarBytes(larguraOcupada-largura);
            }

        }
            break;
    }
            
    return matriz;
}
